package pbx.service;

import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import pbx.model.Queue;
import pbx.model.QueueLogResult;
import util.DateUtil;


@Stateless
public class QueueLogResultService {

	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	@EJB
	DateUtil dateUtil;
	
	
	public QueueLogResult save(QueueLogResult queuelogResult) {
		em.persist(queuelogResult);
		return queuelogResult;   
	}
	
	public QueueLogResult update(QueueLogResult queuelogResult) {
		return em.merge(queuelogResult);
	}
	
	@SuppressWarnings("unchecked")
    public List<QueueLogResult> list(Date startdate, Date enddate, String event, String src, Queue queue ) {
		
		System.out.println("START " + startdate);
		System.out.println("END " + enddate);
		
		//System.out.println("START UTC " + dateUtil.change2UTC(startdate));
		//System.out.println("END UTC " + dateUtil.change2UTC(enddate));
		
	    String sql = "SELECT e FROM QueueLogResult e WHERE e.calldate BETWEEN :startdate AND :enddate ";
	    if(queue!=null){
			sql = sql + " AND e.queue=:queue ";
		}
	    if(event!=null){
			sql = sql + " AND e.event=:event ";
		}
	    if(src!=null){
			sql = sql + " AND e.src=:src ";
		}
		Query query = em.createQuery(sql);
		query.setParameter("startdate", startdate);
		query.setParameter("enddate", enddate);
		if(queue!=null){
			query.setParameter("queue", queue);
		}
		if(event!=null){
			query.setParameter("event", event);
		}
		if(src!=null){
			query.setParameter("src", src);
		}
		return query.getResultList();
	}
	
	
}

